package com.szewec.ps.ui.task;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.base.ListBaseAdapter;
import com.szewec.ps.base.SuperViewHolder;
import com.szewec.ps.databinding.ActivityTaskIndexBinding;
import com.szewec.ps.model.Meta;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.project.ProjectListModel;
import com.szewec.ps.model.task.TaskListModel;
import com.szewec.ps.model.task.TaskUserModel;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.util.DateUtil;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.ContentValues.TAG;

public class TaskIndexActivity extends BaseActivity {
    private ActivityTaskIndexBinding binding;

    private DataAdapter mDataAdapter;

    private ProjectListModel.ProjectModel projectModel = new ProjectListModel.ProjectModel();
    private List<TaskListModel.TaskVO> dataSource = new ArrayList<>();
    private String projectId;
    // 当前点击的第几个item
    private int selectedItem = -1;
    // 总条数
    private Integer TOTAL_COUNTER = -1;
    // 页码
    private Integer _pageIndex = 1;
    // 每页的条数
    private Integer _pageSize = 99999;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_task_index);
        // 获取下拉列表视图

        //初始化样式和相关数据
        initData();
        initTitleBar();
        //初始化适配器
        initRecycleView();
        getTaskList();
    }

    /**
     * 初始化样式和相关数据
     */
    private void initData(){
        // 获取项目ID
        PresentValue<ProjectListModel.ProjectModel> presentValue = (PresentValue<ProjectListModel.ProjectModel>) getIntent().getSerializableExtra(Constants.PRESENT_VALUE);
        Log.i("taskIndexInitData", JSONObject.toJSONString(presentValue));
        projectModel = presentValue.getT();
        projectId = projectModel.getId();
    }

    private void initTitleBar() {
        binding.titleBar.setTitle(projectModel.getProjectName());
        //显示返回按钮
        binding.titleBar.setLeftLayoutVisibility(View.VISIBLE);
        binding.titleBar.setLeftLayoutClickListener(this::finish);
    }

    /**
     * 初始化适配器
     */
    private void initRecycleView() {
        // 初始化任务列表适配器
        mDataAdapter = new DataAdapter(this);
        mDataAdapter.addAll(dataSource);
        binding.lRecyclerView.setAdapter(new LRecyclerViewAdapter(mDataAdapter));
        binding.lRecyclerView.setHasFixedSize(true);
        binding.lRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.lRecyclerView.setLoadMoreEnabled(false);
        binding.lRecyclerView.setPullRefreshEnabled(true);
        binding.lRecyclerView.setArrowImageView(R.drawable.pulltorefresh_pulldown_refresh);
        //设置底部加载文字提示
        binding.lRecyclerView.setFooterViewHint(getResources().getString(R.string.try_loading), getResources().getString(R.string.no_more_data), getResources().getString(R.string.no_network));
        binding.lRecyclerView.setRefreshProgressStyle(23);
        binding.lRecyclerView.setLoadingMoreProgressStyle(23);
        binding.lRecyclerView.refresh();
        binding.lRecyclerView.setOnRefreshListener(() -> {
            //重新初始化相关数据
            dataSource.clear();
            // 查询任务列表
            getTaskList();
        });
    }

    /**
     * 根据项目ID查询任务列表
     */
    private void getTaskList() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("projectId", projectId);
        OkHttp.get("/tpms-plan-service/api/task/list", param, null, (result -> {
            TaskListModel listModel = JSONObject.parseObject(result, TaskListModel.class);
            Meta metaBean = listModel.getMeta();
            TOTAL_COUNTER = metaBean.getTotal() != null ? metaBean.getTotal() : -1;
            if (_pageIndex == 1) {
                dataSource.clear();
            }
            dataSource.addAll(listModel.getData());
            Log.i("taskIndexDataSource", JSONObject.toJSONString(dataSource));

            mDataAdapter.setDataList(dataSource);
            binding.lRecyclerView.refreshComplete(TOTAL_COUNTER);
        }));
    }

    /**
     * 跳转项目详情页面
     */
    private void openDetails(TaskListModel.TaskVO taskVO) {
        Intent intent = new Intent(TaskIndexActivity.this, TaskEditActivity.class);
        // 组装传递对象
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("projectModel", projectModel);
        paramMap.put("taskVO", taskVO);
        Log.i("openDetails", JSONObject.toJSONString(paramMap));
        PresentValue<Map<String, Object>> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.VIEW, paramMap);
        intent.putExtra(Constants.PRESENT_VALUE, presentValue);
        startActivityForResult(intent, PreferincesContext.REQUEST_CODE);
    }


    private class DataAdapter extends ListBaseAdapter<TaskListModel.TaskVO> {
        public DataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_task_cell;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TaskListModel.TaskVO taskVO = mDataList.get(position);
            // 填充数据
            TextView tvTaskMatter = holder.getView(R.id.tv_task_matter); // 任务事项
            TextView tvTaskWorkerUser = holder.getView(R.id.tv_task_worker_user); // 任务人
            TextView tvTaskStartDate = holder.getView(R.id.tv_task_start_date); // 任务开始时间
            TextView tvTaskStatus = holder.getView(R.id.tv_task_status); // 任务状态

            tvTaskMatter.setText(TextViewUtil.convertDataString(taskVO.getTaskMatter()));
            tvTaskWorkerUser.setText(TextViewUtil.convertDataString(StringUtils.getStrWithList(",", taskVO.getWorkerUserList(), TaskUserModel::getUserName)));
            tvTaskStartDate.setText(TextViewUtil.convertDataString(DateUtil.convertDateToString(taskVO.getTaskEndTime(), "yyyy-MM-dd")));
            tvTaskStatus.setText(TextViewUtil.convertDataString(Enums.TaskStatusEnum.getValueByKey(taskVO.getTaskStatus())));

            //行点击监听事件
            holder.itemView.setOnClickListener(view -> {
                openDetails(taskVO);
                if (selectedItem != position) {//增加限制条件，防止重复点击
                    selectedItem = position;
                    mDataAdapter.notifyDataSetChanged();
                }
            });
        }
    }
}
